import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository, UpdateResult } from 'typeorm';
import { Answer } from '../answer/answer.entity';
import { AnswerReportErrors } from './answerReportErrors.entity';
import { CheckEnum, EnumReportDeleteTag, TypeEnum } from './answerReportErrors.enum';
import { CheckEnum as AnswerCheckEnum} from './../answer/answer.enum';
import DataBase from 'src/config/database';
import { Profit } from '../profit/profit.entity';
import { profitEnum } from '../profit/profit.enum';

@Injectable()
export class AnswerReportErrorsService {
  constructor(
    @InjectRepository(AnswerReportErrors)
    private repository: Repository<AnswerReportErrors>,
    @InjectRepository(Answer)
    private answerRepository: Repository<Answer>,
    @InjectRepository(Profit)
    private profitRepository: Repository<Profit>,
  ) {}

  async checkSuccess(id: number): Promise<String | undefined>{
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    
    //查询错误内容
    let findReportError:AnswerReportErrors = await this.repository.findOne({where:{id}})

    try {
      //修改回答为不通过
      await this.answerRepository.createQueryBuilder(null,queryRunner).update({check: 0, check_time: new Date()}).where({id: findReportError.answer_id}).execute()
      //修改报错通过
      await this.repository.createQueryBuilder(null,queryRunner).update({check: CheckEnum.yes, check_time: new Date()}).where({id: id}).execute()
      //删除当前回答的收益记录（仅删除未入账的）
      await this.profitRepository.createQueryBuilder(null,queryRunner).delete().where({answer_id:findReportError.answer_id,status:In([profitEnum.not_entry, profitEnum.entry])}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  checkReject(id: number): Promise<UpdateResult>{
    return this.repository.update({id:id},{check:CheckEnum.no})
  }

  findByWxUser(wx_user: string,answer_id: number, type: TypeEnum): Promise<AnswerReportErrors> {
    return this.repository.findOne({
      where:{wx_user,answer_id:answer_id,type:type},
      order:{create_time:'desc'},
    });
  }

  async findAll_manager(skip: number, take: number, video_id: number): Promise<{dataList:[],total:number}> {
    let params = [skip, take]
    let paramsTotal = []
    if(video_id){
      params.splice(0,0,video_id)
      paramsTotal.push(video_id)
    }
    let answerInfoList = await this.repository.query(`
      select distinct
        video.id as video_id,
        answer_report_errors.id,
        answer_report_errors.type,
        answer_info.ic_name,
        answer_info.create_time,
        answer_info.img,
        answer_info.account,
        answer_info.avatar_img,
        answer_info.platform,
        video.ic_group,
        answer.id as answer_id,
        video.video_url as video_url,
        video.video_url_source,
        video.video_cover, 
        video.type as video_type
      from answer_info
      inner join answer on answer.id = answer_info.answer_id
      inner join answer_report_errors on answer_report_errors.answer_id = answer.id
      inner join video on video.id = answer.video_id
      inner join (
        select answer_report_errors.id from answer_report_errors
				inner join answer on answer.id = answer_report_errors.answer_id
				inner join answer_info on answer_info.answer_id = answer.id
				inner join video on video.id = answer.video_id
        where answer_report_errors.check = 0 ${video_id ? ' and video.id = ?' : ''} and answer_report_errors.source = 0 and answer_report_errors.delete_tag = 0
        order by answer_report_errors.id desc
        limit ?,?
      ) temp on temp.id = answer_report_errors.id
    `, params) 

    let platformList = await this.repository.query(`
      select distinct
        video.id as video_id,
        answer_report_errors.id,
        answer_report_errors.type,
        internet_celebrity.name,
        internet_celebrity.create_time,
        internet_celebrity.img,
        internet_celebrity.account,
        internet_celebrity.avatar_img,
        internet_celebrity.overseas,
        platform.platform,
        video.ic_group,
        answer.id as answer_id,
        video.video_url as video_url,
        video.video_url_source,
        video.video_cover, 
        video.type as video_type
      from internet_celebrity
      inner join video on video.ic_group = internet_celebrity.ic_group
      inner join answer on answer.video_id = video.id
      inner join answer_report_errors on answer_report_errors.answer_id = answer.id
      inner join platform on platform.id = internet_celebrity.platform
      inner join (
        select answer_report_errors.id from answer_report_errors
				inner join answer on answer.id = answer_report_errors.answer_id
				inner join video on video.id = answer.video_id				
				inner join internet_celebrity on internet_celebrity.ic_group = video.ic_group
				inner join platform on platform.id = internet_celebrity.platform
				where answer_report_errors.check = 0 ${video_id ? ' and video.id = ?' : ''} and answer_report_errors.source = 0 and answer_report_errors.delete_tag = 0
        order by answer_report_errors.id desc
        limit ?,?
      ) temp on temp.id = answer_report_errors.id
    `, params) 
    
    let list = [...answerInfoList,...platformList]
    let dataList:any = []
    let setList = [...new Set(list.map(e => e.video_id))]
    setList.map(video_id => {
      let e = list.find(c => c.video_id == video_id)
      if(e.ic_group){
        dataList.push(...platformList.filter(c => c.video_id == e.video_id))
      }else{
        dataList.push(...answerInfoList.filter(c => c.video_id == e.video_id))
      }
    })
    dataList.sort((a,b) => b.id - a.id)
   
    let total = await this.repository.query(`
      select count(*) as total from (
        select distinct
            video.id as video_id,
            answer_report_errors.id,
            internet_celebrity.name,
            internet_celebrity.create_time,
            internet_celebrity.img,
            internet_celebrity.account,
            internet_celebrity.avatar_img,
            internet_celebrity.overseas,
            platform.platform,
            video.ic_group,
            answer.id as answer_id
          from internet_celebrity
          inner join video on video.ic_group = internet_celebrity.ic_group
          inner join answer on answer.video_id = video.id
          inner join answer_report_errors on answer_report_errors.answer_id = answer.id
          inner join platform on platform.id = internet_celebrity.platform
          ${video_id ? ' where video.id = ? and answer_report_errors.source = 0' : ' where answer_report_errors.source = 0'} and answer_report_errors.delete_tag = 0
        ) as temp
    `, paramsTotal)
    return {dataList: dataList,total:Number(total[0].total)}
  }

  async findAll(skip: number, take: number): Promise<{dataList:[],total:number}> {
    let answerInfoList = await this.repository.query(`
      select distinct
        video.id as video_id,
        answer_report_errors.id,
        answer_report_errors.type,
        answer_info.ic_name,
        answer_info.create_time,
        answer_info.img,
        answer_info.account,
        answer_info.avatar_img,
        answer_info.platform,
        video.ic_group,
        answer.id as answer_id
      from answer_info
      inner join answer on answer.id = answer_info.answer_id
      inner join answer_report_errors on answer_report_errors.answer_id = answer.id
      inner join video on video.id = answer.video_id
      inner join (
        select answer_report_errors.id from answer_report_errors
				inner join answer on answer.id = answer_report_errors.answer_id
				inner join answer_info on answer_info.answer_id = answer.id
				inner join video on video.id = answer.video_id
        where answer_report_errors.check = 0
        limit ?,?
      ) temp on temp.id = answer_report_errors.id
      order by video.id desc
    `,[skip, take]) 

    let platformList = await this.repository.query(`
      select distinct
        video.id as video_id,
        answer_report_errors.id,
        answer_report_errors.type,
        internet_celebrity.name,
        internet_celebrity.create_time,
        internet_celebrity.img,
        internet_celebrity.account,
        internet_celebrity.avatar_img,
        internet_celebrity.overseas,
        platform.platform,
        video.ic_group,
        answer.id as answer_id
      from internet_celebrity
      inner join video on video.ic_group = internet_celebrity.ic_group
      inner join answer on answer.video_id = video.id
      inner join answer_report_errors on answer_report_errors.answer_id = answer.id
      inner join platform on platform.id = internet_celebrity.platform
      inner join (
        select answer_report_errors.id from answer_report_errors
				inner join answer on answer.id = answer_report_errors.answer_id
				inner join video on video.id = answer.video_id				
				inner join internet_celebrity on internet_celebrity.ic_group = video.ic_group
				inner join platform on platform.id = internet_celebrity.platform
				where answer_report_errors.check = 0
        limit ?,?
      ) temp on temp.id = answer_report_errors.id
      order by video.id desc
    `,[skip, take]) 
    
    let list = [...answerInfoList,...platformList]
    let dataList:any = []
    let setList = [...new Set(list.map(e => e.video_id))]
    setList.map(video_id => {
      let e = list.find(c => c.video_id == video_id)
      if(e.ic_group){
        dataList.push(...platformList.filter(c => c.video_id == e.video_id))
      }else{
        dataList.push(...answerInfoList.filter(c => c.video_id == e.video_id))
      }
    })
    let total = await this.repository.query(`
      select count(*) as total from (
        select distinct
            video.id as video_id,
            answer_report_errors.id,
            internet_celebrity.name,
            internet_celebrity.create_time,
            internet_celebrity.img,
            internet_celebrity.account,
            internet_celebrity.avatar_img,
            internet_celebrity.overseas,
            platform.platform,
            video.ic_group,
            answer.id as answer_id
          from internet_celebrity
          inner join video on video.ic_group = internet_celebrity.ic_group
          inner join answer on answer.video_id = video.id
          inner join answer_report_errors on answer_report_errors.answer_id = answer.id
          inner join platform on platform.id = internet_celebrity.platform
        ) as temp
    `)
    return {dataList: dataList,total:Number(total[0].total)}
  }

  findOne(id: number): Promise<AnswerReportErrors> {
    return this.repository.findOne({where:{id}});
  }

  async create(data: AnswerReportErrors): Promise<AnswerReportErrors> {
    let findData = await this.repository.findOne({where:{answer_id:data.answer_id,wx_user:data.wx_user,type:data.type}})
    if(findData){
      return findData
    }else{
      return await this.repository.save(data);
    }
  }

  async update(data: AnswerReportErrors): Promise<AnswerReportErrors> {
    return await this.repository.save(data);
  }

  
  deleteTag(id: number): Promise<UpdateResult>{
    return this.repository.update({id:id},{delete_tag: EnumReportDeleteTag.yes})
  }

}
